﻿function ValidateVersion ([string]$version) {
  $versions = $version.Split('.')

  if ($versions.Count -eq 3) {
    $validateNode0 = $(ValidateVersionNode($versions[0]))
    $validateNode1 = $(ValidateVersionNode($versions[1]))
    $validateNode2 = $(ValidateVersionNode($versions[2]))

    if ($validateNode0 -and $validateNode1 -and $validateNode2) {
      return $true
    }
  }

  Write-Host "ERROR: $version 格式不正确" -ForegroundColor Red
  return $false
}

function ValidateVersionNode([string]$node) {
  [int]$value = 0

  if ([int]::TryParse($node, [ref]$value)) {
    return $($value.ToString() -eq $node)
  }

  return $false
}

function CheckCommandExists([string]$cmdName) {
  return [bool](Get-Command -Name $cmdName -ErrorAction SilentlyContinue)
}

function GetLatestVersion ([string[]]$content) {
  for ($i = $content.Count - 1; $i -ge 0 ; $i--) {
    if ($content[$i] -eq '@版本号') {
      $version = $content[$i + 1]
      $description = $content[$i + 3]
      return ($version, $description)
    }
  }
}

# script body

[string]$targetDir = "\\192.168.8.55\information\eb-app\qst-app-htkj"

if (-not (Test-Path $targetDir)) {
  Write-Host "ERROR: $targetDir 路径不存在" -ForegroundColor Red
  exit
}

[string]$targetPublishDir = $targetDir + "\publish"
[string[]]$appsettingsFiles = @("$targetPublishDir\appsettings.json", "$targetPublishDir\appsettings.Development.json")
[string]$versionFile = $targetDir + "\version.txt"

#region 1.Run dotnet publish command
Write-Host "1.Run dotnet publish command:" -ForegroundColor Yellow
dotnet publish -c Release -o $targetPublishDir
#endregion

#region 2.Remove unnecessary appsettings files
Write-Host "`r`n2.Remove unnecessary appsettings files:" -ForegroundColor Yellow

for ($index = 0; $index -lt $appsettingsFiles.Count; $index++) {
  if (Test-Path $appsettingsFiles[$index]) {
    Remove-Item $appsettingsFiles[$index]
    Write-Host "removed $($appsettingsFiles[$index])" -ForegroundColor Green
  }
}
#endregion

#region 3.Input new version information
Write-Host "`r`n3.Update application version:" -ForegroundColor Yellow

[string[]]$results = GetLatestVersion((Get-Content $versionFile))
[string]$preVersionText = $results[0].split(':')[0].Substring(1)
[int[]]$preVersions = $preVersionText.Split('.')
[int]$major = $preVersions[0]
[int]$minor = $preVersions[1]
[int]$patch = $preVersions[2]

Write-Host "`The previous application version is ""$preVersionText""" -ForegroundColor Green
Write-Host "`The previous application version note is ""$($results[1])""" -ForegroundColor Green

$majorOption = New-Object System.Management.Automation.Host.ChoiceDescription "&z:主版本号", "MAJOR version: 当你做了不兼容的 API 修改"
$minorOption = New-Object System.Management.Automation.Host.ChoiceDescription "&c:次版本号", "MINOR version: 当你做了向下兼容的功能性新增"
$patchOption = New-Object System.Management.Automation.Host.ChoiceDescription "&x:修订号", "PATCH version: 当你做了向下兼容的问题修正"
$defaultOption = New-Object System.Management.Automation.Host.ChoiceDescription "&d:自定义", "不适用自增加一的方式，请根据 [主版本号].[次版本号].[修订号] 的格式填写"

$options = [System.Management.Automation.Host.ChoiceDescription[]](
  $majorOption,
  $minorOption,
  $patchOption,
  $defaultOption
)

$selectedChoice = $Host.UI.PromptForChoice("Select update way", "请选择此版本的改动程度，选择后会在上个版本号对应的节点加一：`r`n主版本号：当你做了不兼容的 API 修改`r`n次版本号：当你做了向下兼容的功能性新增`r`n修订号：当你做了向下兼容的问题修正`r`nmore details: https://semver.org/lang/zh-CN/", $options, 2)

[string]$newVersion
switch ($selectedChoice) {
  0 {
    $newVersion = "v$($major + 1).0.0"
  }
  1 {
    $newVersion = "v$($major).$($minor + 1).0"
  }
  2 {
    $newVersion = "v$($major).$($minor).$($patch + 1)"
  }
  Default {
    while ($true) {
      Write-Host "`请输入格式为 [主版本号].[次版本号].[修订号] 的版本号:" -ForegroundColor Yellow
      $newVersion = Read-Host

      if (ValidateVersion($newVersion)) {
        if (!$newVersion.StartsWith('v')) {
          $newVersion = "v$newVersion"
          break
        }
      }
    }
  }
}

Write-Host "Please input application version note:" -ForegroundColor Yellow
[string]$versionNoteInput = Read-Host

[string]$robotCommand = "jenkins build qst-app&NAME_DIR=qst-app-htkj"
$robotCommand += "&VERSION=$newVersion"
$robotCommand += "&DESCRIBE=$versionNoteInput"

Write-Host "Please copy the robot command below and paste it to the Rocket.Chat input:" -ForegroundColor Yellow
Write-Host $robotCommand -ForegroundColor Green

if (CheckCommandExists("clip.exe")) {
   $robotCommand | clip.exe
   Write-Host 'Copied!!!' -ForegroundColor Magenta
}
elseif (CheckCommandExists("Set-ClipBoard")) {
  $robotCommand | Set-ClipBoard
  Write-Host 'Copied!!!' -ForegroundColor Magenta
}

Start-Process "http://192.168.8.248:3000/group/myjenkins"
#endregion